package com.azxc.rapid.plus.user.feign;

import com.azxc.rapid.core.log.exception.ServiceException;
import com.azxc.rapid.core.mp.support.Condition;
import com.azxc.rapid.core.secure.utils.AuthUtil;
import com.azxc.rapid.core.tenant.annotation.NonDS;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.core.tool.utils.BeanUtil;
import com.azxc.rapid.core.tool.utils.Func;
import com.azxc.rapid.plus.user.dto.PageFeign;
import com.azxc.rapid.plus.user.entity.UserEntity;
import com.azxc.rapid.plus.user.mapper.UserPlusMapper;
import com.azxc.rapid.plus.user.service.IUserEntityService;
import com.azxc.rapid.plus.user.service.IUserPlusService;
import com.azxc.rapid.plus.user.service.IWestoneStaffService;
import com.azxc.rapid.plus.user.vo.WestoneBaseMsg;
import com.azxc.rapid.system.cache.SysCache;
import com.azxc.rapid.system.entity.Dept;
import com.azxc.rapid.system.user.entity.User;
import com.azxc.rapid.system.user.service.IUserService;
import com.azxc.rapid.system.user.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * @author linym
 * @className: UserPlusClient
 * @description:
 * @date 2022/8/23 15:53
 * @version：1.0
 */
@NonDS
@ApiIgnore
@RestController
@AllArgsConstructor
public class UserPlusClient implements IUserPlusClient {
	private final IUserService service;
	private final UserPlusMapper userMapper;

	private final IUserPlusService userPlusService;
	private final IWestoneStaffService westoneStaffService;

	private final IUserEntityService userEntityService;

	@Override
	public R<UserVO> getUserInfo() {
		return R.data(service.getUserVoInfo());
	}


	@Override
	public R<List<UserVO>> getUserListInfo(String deptId) {
		User user = new User();
		user.setDeptId(deptId);
		user.setIsDeleted(0);
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user);
		List<User> list = service.list((!AuthUtil.isAdministrator()) ? queryWrapper.lambda() : queryWrapper);
		return R.data(BeanUtil.copy(list, UserVO.class));
	}


	@Override
	public R<List<String>> selectJudgeUser(Long userId) {
		User user = userMapper.selectById(userId);
		Dept dept = SysCache.getDept(Func.toLong(user.getDeptId()));
		String regionCode = Func.toStr(dept.getRegionCode());
		if (4 < regionCode.length()) {
			regionCode = regionCode.substring(0, regionCode.length() - 2);
		}
		//todo 这里角色ID 不应该写死
		List<String> userIdList = selectRoleId(1427452123260383233L, regionCode);
		return R.data(userIdList);
	}

	@Override
	public R<List<String>> selectFoodDirectorUser(Long userId) {
		User user = userMapper.selectById(userId);
		Dept dept = SysCache.getDept(Func.toLong(user.getDeptId()));
		String regionCode = Func.toStr(dept.getRegionCode());
		if (2 < regionCode.length()) {
			regionCode = regionCode.substring(0, regionCode.length() - 2);
		}
		List<String> userList = selectRoleId(1427451889511821313L, regionCode);
		return R.data(userList);
	}

	@Override
	public R<List<String>> selectProEmerLeader(Long userId) {
		User user = userMapper.selectById(userId);
		Dept dept = SysCache.getDept(Func.toLong(user.getDeptId()));
		String regionCode = Func.toStr(dept.getRegionCode());
		if (2 < regionCode.length()) {
			regionCode = regionCode.substring(0, regionCode.length() - 2);
		}
		List<String> userList = selectRoleId(1427451932956422146L, regionCode);
		return R.data(userList);
	}

	@Override
	public R<List<String>> selectProLeader(Long userId) {
		User user = userMapper.selectById(userId);
		Dept dept = SysCache.getDept(Func.toLong(user.getDeptId()));
		String regionCode = Func.toStr(dept.getRegionCode());
		if (2 < regionCode.length()) {
			regionCode = regionCode.substring(0, regionCode.length() - 2);
		}
		List<String> userList = selectRoleId(1427451969132294145L, regionCode);
		return R.data(userList);
	}

	@Override
	public R<List<User>> userListByIds(String userIds) {
		List<User> users = service.listByIds(Func.toLongList(userIds));
		return R.data(users);
	}

	@Override
	public R<List<User>> selectUserByRegionCode(String regionCode) {
		List<User> userList = userMapper.selectUserByRegionCode(regionCode);
		return R.data(userList);
	}

	@Override
	public R<User> userByName(String userName, String deptName) {
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(User::getRealName,userName);
		return R.data(service.getOne(queryWrapper));
	}

	@Override
	public R<UserEntity> getEntityByUser(String userId) {
		UserEntity userEntity = new UserEntity();
		userEntity.setUserId(Long.valueOf(userId));
		UserEntity detail = userEntityService.getOne(
			Condition.getQueryWrapper(userEntity).last("limit 1"));
		return R.data(detail);
	}

	public List<String> selectRoleId(Long roleId, String region) {
		List<String> userList = userMapper.selectUserByRoleId(roleId, region);
		return userList;
	}


	@Override
	public R<Boolean> saveEnterpriseUser(User user) {
		return R.data(service.submit(user));
	}


	@Override
	public R<Boolean> updateUserByAccount(String oldAccount,String newAccount,String newName){
		User user = service.getOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, oldAccount));
		if(newAccount != null ){
			user.setAccount(newAccount);
		}
		if(newName != null ){
			user.setName(newName);
			user.setRealName(newName);
		}
		boolean temp =  service.updateById(user);
		return R.data(temp);
	}

	@Override
	public R<Boolean> resetPasswordByAccount(String account) {
		User user = service.getOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, account));
		boolean temp = service.resetPassword(user.getId()+"");
		return R.data(temp);
	}

	@Override
	public R<Boolean> sendMsgToWestoneByMobile(WestoneBaseMsg westoneBaseMsg) {
		return R.status(westoneStaffService.pushMessageByMobile(westoneBaseMsg.getRecipients(),westoneBaseMsg.getBadge_number(),
			westoneBaseMsg.getMsgType(), westoneBaseMsg.getSubject(), westoneBaseMsg.getContent(), westoneBaseMsg.getActions()));
	}

	/**
	 * 获取当前用户所属部门，并通过部门获取绑定的行政区划编码regionCode
	 */
	@Override
	public R<String> getRegionCode() {
		Dept dept = SysCache.getDept(Long.parseLong(AuthUtil.getDeptId()));
		if (null == dept || null == dept.getId()) {
			throw new ServiceException("获取登录人所在部门失败!");
		}
		String region = dept.getRegionCode();
		return R.data(region);
	}

	@GetMapping(USER_PAGE)
	@Override
	public R<PageFeign<User>> userPage(Integer current, Integer size) {
		Page<User> page = service.page(new Page<>(current, size));
		PageFeign<User> objectPageFeign = new PageFeign<>(page);
		return R.data(objectPageFeign);
	}


	@Override
	public R<List<Long>> getStorageByUserId() {
		return R.data(userPlusService.getStorageIdList());
	}


	@GetMapping(USER_TRACE_INSTITUTE)
	@Override
	public R<PageFeign<User>> userTraceInstitute(Integer current, Integer size) {
		IPage<User> page = userPlusService.userByRoleTraceInstitute(new Page<>(current, size));
		PageFeign<User> objectPageFeign = new PageFeign<>(page);
		return R.data(objectPageFeign);
	}




	@GetMapping(GET_USER_INFO_BATCH)
	@Override
	public R<List<User>> userInfoBatch(String userIds) {
		List<String> temp = Func.toStrList(userIds);
		if (temp.size() <= 0) {
			return R.data(new ArrayList<>());
		}
		List<User> user = service.list(
			Wrappers.<User>lambdaQuery().in(User::getId, temp)
		);
		return R.data(user);
	}

	@Override
	public void updateUserEntId(User user) {
		userMapper.updateUserEntId(user);
	}



	@GetMapping(USER_BY_REGION_CODE)
	@Override
	public R<List<User>> getUserByRegionCode(String regionCodes) {
		return R.data(userMapper.userByRegionCode(Func.toStrList(regionCodes)));
	}
}
